﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EasyPiano
{
    public partial class MusicRecordManagerForm : Form
    {
        public MusicRecord record;

        List<MusicScoreControl> musicScoreControls = new List<MusicScoreControl>();
        Thread listenThread;
        bool isPause = true;
        bool isDestory = false;
        int selectedLabelIndex = -1;
        int progress = 0;
        float playSpeed = 1;
        int totolProgress;

        HashSet<int> greenIndex = new HashSet<int>();

        public MusicRecordManagerForm()
        {
            InitializeComponent();            
        }

        private void MusicScoreControl_Click(object sender, EventArgs e)
        {
            CancelSelectedLabel();
            SelectLabel((MusicScoreControl)sender);
        }

        private void AddLabelToUI(string text, float delay = 1, bool visible = true)
        {
            MusicScoreControl msControl = new MusicScoreControl();
            msControl.SoundStr1 = text;
            msControl.Click += new EventHandler(MusicScoreControl_Click);
            msControl.Delay = (int)delay;
            if (visible == true)
            {
                musicScoreControls.Add(msControl);
                flp_music.Controls.Add(msControl);
            }
            else
            {
                musicScoreControls.Add(null);
                flp_music.Controls.Add(null);
            }
        }

        private void CancelSelectedLabel()
        {
            if (selectedLabelIndex != -1)
            {
                musicScoreControls[selectedLabelIndex].CancelSelect();
                selectedLabelIndex = -1;
            }
        }
        private void SelectLabel(MusicScoreControl msControl)
        {
            msControl.Selected();
            selectedLabelIndex = musicScoreControls.IndexOf(msControl);
        }

        private void MusicScoreManagerForm_Load(object sender, EventArgs e)
        {
            totolProgress = record.TotalProgress;
            //添加播放线程
            listenThread = new Thread(MusicPlay);
            listenThread.IsBackground = false;
            listenThread.Start();

            //to-do bug
            for (int i = 0; i < totolProgress; i++)
            {
                if (record.mode == 0)
                {
                    AddLabelToUI(Util.SoundIndexToString(record.GetSimple(i).soundIndex),
                    record.GetSimple(i).duration / 1000);
                }
                else
                {                    
                    if(record.GetContinue(i).state)
                    {
                        int afIndex = record.FindEqualAfter(i, record.GetContinue(i).soundIndex);
                        AddLabelToUI(Util.SoundIndexToString(record.GetContinue(i).soundIndex),
                       (record.GetContinue(afIndex).time - record.GetContinue(i).time) / 1000);
                    }
                    else
                    {
                        AddLabelToUI("0", 1, false);
                    }
                }
            }

            cb_play_speed.SelectedIndex = 1;
            lb_musicName.Text = record.musicName;
            lb_author.Text = record.author;
        }

        private void bt_listen_Click(object sender, EventArgs e)
        {
            if (musicScoreControls.Count > 0)
            {
                if (record.mode == 1)
                {
                    Util.StopAllPlay();                    
                }

                CancelAll();

                isPause = false;
                progress = 0;
                CancelSelectedLabel();
            }
        }

        private void bt_stop_Click(object sender, EventArgs e)
        {
            isPause = true;
            if (record.mode == 1)
                Util.StopAllPlay();
        }

        private void bt_resume_Click(object sender, EventArgs e)
        {
            isPause = false;
            CancelAll();
        }

        private void MusicScoreManagerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            isPause = true;
            isDestory = true;
            Util.StopAllPlay();
        }        

        private void bt_jump_Click(object sender, EventArgs e)
        {
            if (selectedLabelIndex != -1)
            {
                if (record.mode == 1)
                    Util.StopAllPlay();

                CancelAll();
                progress = selectedLabelIndex;
                isPause = false;
                CancelSelectedLabel();                
            }
        }

        private void cb_play_speed_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = cb_play_speed.SelectedIndex;
            if (index == 1)
                playSpeed = 1;
            else if (index == 0)
                playSpeed = 2;
            else if (index == 2)
                playSpeed = 0.5f;
        }

        private void MusicPlay()
        {
            while (isDestory == false)
            {
                if (isPause)
                    continue;

                while (progress < totolProgress)
                {
                    if (record.mode == 0)
                    {
                        if (progress > 0)//取消后一个的绿色
                        {
                            musicScoreControls[progress - 1].CancelSelect();
                            greenIndex.Remove(progress - 1);
                        }
                        //设置当前为绿色
                        musicScoreControls[progress].Playing();
                        greenIndex.Add(progress);
                        //播放
                        int index = record.GetSimple(progress).soundIndex;
                        if (index > 0)
                        {
                            Util.AsynPlaySound(GlobalData.soundsPath[index]);                           
                        }

                        progress++;

                        //等待
                        Thread.Sleep((int)(record.GetSimple(progress - 1).duration * playSpeed));
                        
                        if (isPause)
                        {
                            break;
                        }
                    }
                    else
                    {
                        //计算时间差
                        int s = 0;
                        if (progress > 0)
                        {
                            s = record.GetContinue(progress - 1).time;
                        }
                        progress++;
                        int progress2 = progress - 1;
                        //等待
                        Thread.Sleep((int)(record.GetContinue(progress2).time - s));

                        if (isPause)
                        {
                            break;
                        }

                        if (progress2 != progress - 1)
                        {
                            continue;
                        }

                        var musicScore2 = record.GetContinue(progress2);

                        if (musicScore2.state)//播放
                        {
                            //设置当前为绿色
                            musicScoreControls[progress2].Playing();
                            greenIndex.Add(progress2);
                            //播放
                            int start_index = musicScore2.soundIndex;
                            if (start_index > 0)
                                Util.StartPlay(start_index);
                        }
                        else//停止
                        {
                            int stop_index = musicScore2.soundIndex;
                            //取消当前的绿色
                            int can_index = record.FindEqualBefore(progress2, stop_index);
                            musicScoreControls[can_index].CancelSelect();
                            greenIndex.Remove(can_index);
                            //停止
                            if (stop_index > 0)
                                Util.StopPlay(stop_index);
                        }
                    }

                                   
                }

                if (isPause == false)//播放完毕
                {
                    progress = 0;

                    if (record.mode == 0)
                    {
                        if (totolProgress > 0)
                            musicScoreControls[totolProgress - 1].CancelSelect();
                    }

                    isPause = true;
                }
            }
        }

        private void CancelAll()
        {
            foreach (var index in greenIndex)
            {
                musicScoreControls[index].CancelSelect();
            }
            greenIndex.Clear();
        }
    }
}
